package com.guqin.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guqin.interview.mapper.QuestionHistoryMapper;
import com.guqin.interview.model.entity.Question;
import com.guqin.interview.model.entity.QuestionHistory;
import com.guqin.interview.model.vo.DailyQuestionCountVO;
import com.guqin.interview.model.vo.QuestionHistoryVO;
import com.guqin.interview.service.QuestionHistoryService;
import com.guqin.interview.service.QuestionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.time.LocalDateTime;

/**
 * 题目历史服务实现
 */
@Service
public class QuestionHistoryServiceImpl extends ServiceImpl<QuestionHistoryMapper, QuestionHistory> implements QuestionHistoryService {

    @Resource
    private QuestionService questionService;

    @Override
    public boolean recordQuestionView(Long userId, Long questionId) {
        if (userId == null || questionId == null) {
            return false;
        }
        QuestionHistory history = new QuestionHistory();
        history.setUserId(userId);
        history.setQuestionId(questionId);
        return this.save(history);
    }

    @Override
    public List<QuestionHistoryVO> getUserQuestionsByDate(Long userId, Date date) {
        if (userId == null || date == null) {
            return Collections.emptyList();
        }

        // 设置查询的时间范围（当天0点到23:59:59）
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startTime = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endTime = calendar.getTime();

        // 查询历史记录
        QueryWrapper<QuestionHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .between("createTime", startTime, endTime)
                .select("questionId, COUNT(*) as count, MIN(createTime) as firstViewTime")
                .groupBy("questionId")
                .orderByDesc("firstViewTime");
        List<Map<String, Object>> historyMaps = this.listMaps(queryWrapper);

        // 获取题目ID列表
        List<Long> questionIds = historyMaps.stream()
                .map(map -> (Long) map.get("questionId"))
                .collect(Collectors.toList());

        // 查询题目详情
        if (questionIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<Question> questionList = questionService.listByIds(questionIds);
        
        // 构建返回结果
        return questionList.stream()
                .map(question -> {
                    QuestionHistoryVO vo = new QuestionHistoryVO();
                    vo.setQuestion(question);
                    
                    // 找到对应的历史记录
                    historyMaps.stream()
                            .filter(map -> map.get("questionId").equals(question.getId()))
                            .findFirst()
                            .ifPresent(map -> {
                                vo.setHistoryTime((LocalDateTime) map.get("firstViewTime"));
                                vo.setCount(((Long) map.get("count")).intValue());
                            });
                    
                    return vo;
                }).collect(Collectors.toList());
    }

    @Override
    public List<DailyQuestionCountVO> getYearlyQuestionCount(Long userId, Integer year) {
        if (userId == null) {
            return Collections.emptyList();
        }

        // 如果年份为空，使用当前年份
        if (year == null) {
            Calendar calendar = Calendar.getInstance();
            year = calendar.get(Calendar.YEAR);
        }

        // 设置查询的时间范围（年初到年末）
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, Calendar.JANUARY, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startTime = calendar.getTime();

        calendar.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endTime = calendar.getTime();

        // 查询历史记录
        QueryWrapper<QuestionHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .between("createTime", startTime, endTime)
                .select("DATE(createTime) as date, COUNT(*) as count")
                .groupBy("DATE(createTime)")
                .orderByAsc("DATE(createTime)");

        // 执行查询并转换结果
        return this.listMaps(queryWrapper).stream()
                .map(map -> {
                    DailyQuestionCountVO vo = new DailyQuestionCountVO();
                    vo.setDate((Date) map.get("date"));
                    vo.setCount(((Long) map.get("count")).intValue());
                    return vo;
                })
                .collect(Collectors.toList());
    }
} 